/**
 * 天气API服务
 * 用于获取城市天气数据
 */
import weatherApi from '@/views/plugin/dashboard/api/weatherApi'

/**
 * 获取城市天气数据
 * @param {string} cityCode - 城市编码
 * @returns {Promise} - 返回天气数据Promise
 */
export const getWeatherByCityCode = async (cityCode) => {
	try {
		const response = await weatherApi.getWeatherByCityCode({ cityCode })
		if (response) {
			// 解析返回的JSON字符串
			const weatherData = JSON.parse(response)
			if (weatherData && weatherData.status === 200) {
				return {
					success: true,
					data: weatherData
				}
			} else {
				return {
					success: false,
					message: weatherData?.message || '获取天气数据失败'
				}
			}
		} else {
			return {
				success: false,
				message: response?.message || '获取天气数据失败'
			}
		}
	} catch (error) {
		console.error('获取天气数据出错:', error)
		return {
			success: false,
			message: error.message || '网络请求失败，请稍后重试'
		}
	}
}

/**
 * 解析天气类型，返回对应的图标key
 * @param {string} weatherType - 天气类型描述
 * @returns {string} - 对应的图标key
 */
export const parseWeatherType = (weatherType) => {
	if (!weatherType) return 'weather01' // 默认晴天图标

	// 根据天气类型返回对应的图标key
	if (weatherType.includes('晴')) return 'weather01'
	if (weatherType.includes('多云')) return 'weather02'
	if (weatherType.includes('阴')) return 'weather03'
	if (weatherType.includes('小雨')) return 'weather04'
	if (weatherType.includes('中雨') || weatherType.includes('大雨')) return 'weather05'
	if (weatherType.includes('雷')) return 'weather06'
	if (weatherType.includes('雪')) return 'weather07'
	if (weatherType.includes('雾') || weatherType.includes('霾')) return 'weather08'
	if (weatherType.includes('风')) return 'weather09'
	if (weatherType.includes('沙尘')) return 'weather10'

	// 默认返回晴天图标
	return 'weather01'
}

/**
 * 格式化天气数据为组件所需格式
 * @param {Object} weatherData - API返回的天气数据
 * @returns {Object} - 格式化后的天气数据
 */
export const formatWeatherData = (weatherData) => {
	if (!weatherData || !weatherData.data) {
		return null
	}

	const { cityInfo, data } = weatherData

	return {
		cityName: cityInfo.city,
		date: data.forecast[0].ymd,
		week: data.forecast[0].week,
		temperature: data.wendu,
		humidity: data.shidu,
		quality: data.quality,
		weatherType: data.forecast[0].type,
		weatherIconKey: parseWeatherType(data.forecast[0].type),
		notice: data.forecast[0].notice,
		highTemp: data.forecast[0].high.replace('高温 ', ''),
		lowTemp: data.forecast[0].low.replace('低温 ', ''),
		forecast: data.forecast.slice(1, 5).map((item) => ({
			date: item.ymd,
			week: item.week,
			weatherType: item.type,
			weatherIconKey: parseWeatherType(item.type),
			highTemp: item.high.replace('高温 ', ''),
			lowTemp: item.low.replace('低温 ', '')
		}))
	}
}
